package com.bolt.admin.common.base;

import com.bolt.common.reflect.ObjectUtil;
import com.bolt.common.utils.StrUtil;
import com.bolt.convention.exception.ServiceException;
import com.bolt.support.spring.jpa.entity.PersistableEntity;
import com.bolt.support.ui.tree.helper.TreeRenderHelper;
import com.bolt.support.ui.tree.model.TreeDataProvider;
import com.bolt.support.ui.tree.vo.UITreeNode;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by mi on 2017/9/29.
 */
public abstract class BaseController<T extends PersistableEntity, ID extends Serializable> extends SimpleController{

    protected final Log logger = LogFactory.getLog(getClass());

    protected Class <T> entityClass;

    protected Class <ID> entityIdClass;


    /**
     * 初始化构造方法，计算相关泛型对象
     */
    public BaseController() {
        super();
        // 通过反射取得Entity的Class.
        try {
            entityClass = (Class <T>) ObjectUtil.getTypeArgument(this, 0);
            entityIdClass = (Class <ID>) ObjectUtil.getTypeArgument(this, 1);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage(), e);
        }
    }



    /**
     * 将指定参数转换为ID泛型对应的主键变量实例
     *
     * @return ID泛型对象实例
     */
    @SuppressWarnings("unchecked")
    public ID getId(String entityId) {
        if (StrUtil.isBlank(entityId) || entityId.startsWith("-")) {
            return null;
        }
        if (String.class.isAssignableFrom(entityIdClass)) {
            return (ID) entityId;
        } else if (Long.class.isAssignableFrom(entityIdClass)) {
            return (ID) (Long.valueOf(entityId));
        } else if (Integer.class.isAssignableFrom(entityIdClass)) {
            return (ID) (Integer.valueOf(entityId));
        } else {
            throw new IllegalStateException("Undefine entity ID class: " + entityIdClass);
        }
    }

    /**
     * 生成树形组件前端数据
     *
     * @param provider 　树形数据提供接口
     * @param nodeId   树形节点ID
     * @param params   前端传入的查询参数
     * @return
     */
    protected List <UITreeNode> getTreeNodes(TreeDataProvider provider, String nodeId, boolean loadAllNodes, Map <String, String> params) {

        List <UITreeNode> dataArray = new ArrayList <>();
        TreeRenderHelper.buildNodesTreeView(provider, getId(nodeId), params, dataArray, loadAllNodes);
        return dataArray;

    }


}
